//
//  CodeView.swift
//  CodeView
//
//  Created by qi long chen on 2021/9/9.
//

import UIKit

class ZYCodeView: UIView {
        
    var code: String = ""
    private var config: ZYCodeConfig!
    private var containerView: UIView!
    private var tmpTextView: UITextView!
    private var codeTexts = [ZYTextView]()
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
    }
    
    init(frame: CGRect, config: ZYCodeConfig) {
        super.init(frame: frame)
        self.config = config
        setUI()
    }
    
    private func setUI() {
        
        tmpTextView = UITextView(frame: self.bounds)
        tmpTextView.delegate = self
        tmpTextView.tintColor = .clear
        containerView = UIView(frame: tmpTextView.bounds)
        containerView.backgroundColor = .white
        
        addSubview(tmpTextView)
        addSubview(containerView)
        
        layoutCodeView()
    }
    
    private func layoutCodeView() {
        
        let h_space: CGFloat = 10
        let count: Int = config.count
        let totalSpace: CGFloat = CGFloat((count - 1)) * h_space
        let defaultSize = CGSize(width: (self.containerView.bounds.width - totalSpace)/CGFloat(count) , height: self.containerView.bounds.height)
        
        for i in 0 ..< config.count {
            let textView = ZYTextView(frame: CGRect(x: CGFloat(i) * (defaultSize.width + h_space), y: 0, width: defaultSize.width, height: defaultSize.height))
            containerView.addSubview(textView)
            codeTexts.append(textView)
        }
    }
    
    /// 让UITextField变成第一响应者, 弹出键盘
    override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
        
        // 如果点击事件不在containerView上,不要响应
        if !containerView.bounds.contains(point) {
            return nil
        }
        
        tmpTextView.becomeFirstResponder()
        // 取消所有光标闪烁
        codeTexts.forEach { codeView in
            codeView.hiddenAnimation()
        }
        
        var current = 0
        if code.count  < codeTexts.count {
            if code.isEmpty {
                current = 0
            }else {
                current = code.count + 1
            }
            if current < config.count {
                let codeView = codeTexts[current]
                codeView.showAnimation()
            }
        }
        return containerView
    }
}

extension ZYCodeView: UITextViewDelegate {
    
    func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
        
        if text == "\n" {
            if range.location == config.count {
                // 最后一位回车键
                code = textView.text
                textView.resignFirstResponder()
            }
            return false
        }
        // 取消所有光标闪烁
        codeTexts.forEach { codeView in
            codeView.hiddenAnimation()
        }
        let digit = range.location
        if digit > config.count - 1 {
            if text.isEmpty {
                // 删除键
                return true
            }
            return false
        }
        
        let codeView = codeTexts[range.location]
        codeView.text.text = text
        if range.length == 0 {
            var nextCodeView: ZYTextView!
            if range.location == 0 {
                if text.isEmpty {
                    nextCodeView = codeTexts[range.location]
                }else {
                    nextCodeView = codeTexts[range.location + 1]
                }
                nextCodeView.showAnimation()
            }else {
                if range.location + 1 < config.count {
                    nextCodeView = codeTexts[range.location + 1]
                    nextCodeView.showAnimation()
                }else {
                    nextCodeView = codeTexts[range.location]
                    nextCodeView.hiddenAnimation()
                }
            }
        }else {
            let nextCodeView = codeTexts[range.location]
            nextCodeView.showAnimation()
        }
        return true
    }
}
